package com.jason.config;

import com.jason.um.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName JwtVerifyInterceptor
 * @Description TODO
 * @Author Jason
 * @Date 2019/1/24 15:02
 * @Version 1.0
 **/
public class JwtHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

        System.out.println("jwt 拦截器验证");
        System.out.println(req);
        System.out.println(res);
        System.out.println(handler);
        String bearerToken  = req.getHeader("Authorization");
        String token = StringUtils.delete(bearerToken, "Bearer ");
        System.out.println("Authorization:" + token);
        
        try {
            Claims claims = JWTUtil.parseJWT(token);
            if (!ObjectUtils.isEmpty(claims)){
                req.setAttribute("claims", claims);
                return true;
            }
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
